package role

import (
	"context"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RoleListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRoleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RoleListLogic {
	return &RoleListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RoleListLogic) RoleList(req *types.RoleListRo) (resp *types.RoleListRsp, err error) {
	var roles []model.RoleConfig
	sess := l.svcCtx.DB.WithContext(l.ctx).Model(&model.RoleConfig{}).Where("1=1")

	var total int64
	if err := sess.Count(&total).Error; err != nil {
		return nil, err
	}
	resp = new(types.RoleListRsp)
	resp.Total = total

	if err := sess.Order("ID DESC").Limit(req.Size).Offset((req.Page - 1) * req.Size).
		Find(&roles).Error; err != nil {
		return nil, err
	}

	for _, v := range roles {
		resp.Items = append(resp.Items, types.RoleWithId{
			RoleId: v.ID,
			Role: types.Role{
				Name:   v.Name,
				IsRoot: v.IsRoot,
				Status: int(v.Status),
				Memo:   v.Memo,
			},
		})
	}

	return
}
